<?php
namespace plugin\ky_black\app\admin\controller;

use support\Request;
use support\Response;
use plugin\ky_black\app\admin\model\ProductCategory;

class ProductCategoryController extends BaseController
{
    /**
     * 获取分类列表
     * @param Request $request
     * @return Response
     */
    public function list(Request $request): Response
    {
        $query = ProductCategory::query();
        
        // Debug: 输出接收到的参数
        var_dump($request->all());
        
        // 查询条件
        $params = $request->get('params', []);
        if (!empty($params['name'])) {
            $query->where('name', 'like', "%{$params['name']}%");
        }
        if (isset($params['status']) && $params['status'] !== '') {
            $query->where('status', $params['status']);
        }

        // Debug: 输出SQL语句
        $query->toSql();
        var_dump($query->getBindings());

        // 获取所有分类
        $categories = $query->orderBy('sort', 'desc')
            ->orderBy('category_id', 'asc')
            ->get();

        // Debug: 输出查询结果
        var_dump($categories->toArray());

        // 构建树形结构
        $tree = $this->buildTree($categories);

        return $this->success([
            'list' => $tree
        ]);
    }

    /**
     * 构建树形结构
     * @param $categories
     * @param $parentId
     * @return array
     */
    private function buildTree($categories, $parentId = 0)
    {
        $tree = [];
        foreach ($categories as $category) {
            if ($category['parent_id'] == $parentId) {
                $item = $category;
                $children = $this->buildTree($categories, $category['category_id']);
                if (!empty($children)) {
                    $item['children'] = $children;
                }
                $tree[] = $item;
            }
        }
        
        // Debug: 输出构建的树形结构
        if ($parentId === 0) {
            var_dump("Final Tree Structure:", $tree);
        }
        
        return $tree;
    }

    /**
     * 添加分类
     * @param Request $request
     * @return Response
     */
    public function add(Request $request): Response
    {
        $data = $request->post();
        
        // 设置层级
        if (empty($data['parent_id'])) {
            $data['level'] = 1;
        } else {
            $parent = ProductCategory::find($data['parent_id']);
            if (!$parent) {
                return $this->error('上级分类不存在');
            }
            $data['level'] = $parent->level + 1;
        }

        $category = new ProductCategory();
        $category->fill($data);
        $category->status = $data['status'] ?? 1;
        
        if ($category->save()) {
            return $this->success(['category_id' => $category->category_id], '添加成功');
        }
        return $this->error('添加失败');
    }

    /**
     * 编辑分类
     * @param Request $request
     * @return Response
     */
    public function edit(Request $request): Response
    {
        $data = $request->post();
        $category = ProductCategory::find($data['category_id']);
        if (!$category) {
            return $this->error('分类不存在');
        }

        // 检查是否修改了父级
        if (isset($data['parent_id']) && $data['parent_id'] != $category->parent_id) {
            if ($data['parent_id'] == $category->category_id) {
                return $this->error('不能选择自己作为父级分类');
            }
            // 检查是否选择了自己的子分类作为父级
            $children = $this->getAllChildren($category->category_id);
            if (in_array($data['parent_id'], $children)) {
                return $this->error('不能选择子分类作为父级分类');
            }
            // 更新层级
            if (empty($data['parent_id'])) {
                $data['level'] = 1;
            } else {
                $parent = ProductCategory::find($data['parent_id']);
                if (!$parent) {
                    return $this->error('上级分类不存在');
                }
                $data['level'] = $parent->level + 1;
            }
        }
        
        $category->fill($data);
        if ($category->save()) {
            return $this->success(['category_id' => $category->category_id], '编辑成功');
        }
        return $this->error('编辑失败');
    }

    /**
     * 获取所有子分类ID
     * @param int $categoryId
     * @return array
     */
    private function getAllChildren($categoryId)
    {
        $children = [];
        $categories = ProductCategory::where('parent_id', $categoryId)->get();
        foreach ($categories as $category) {
            $children[] = $category->category_id;
            $children = array_merge($children, $this->getAllChildren($category->category_id));
        }
        return $children;
    }

    /**
     * 删除分类
     * @param Request $request
     * @return Response
     */
    public function delete(Request $request): Response
    {
        $categoryId = $request->input('category_id');
        $category = ProductCategory::find($categoryId);
        if (!$category) {
            return $this->error('分类不存在');
        }

        // 检查是否有子分类
        $hasChildren = ProductCategory::where('parent_id', $categoryId)->exists();
        if ($hasChildren) {
            return $this->error('请先删除子分类');
        }

        if ($category->delete()) {
            return $this->success([], '删除成功');
        }
        return $this->error('删除失败');
    }

    /**
     * 更新分类状态
     * @param Request $request
     * @return Response
     */
    public function status(Request $request): Response
    {
        $categoryId = $request->input('category_id');
        $status = $request->input('status');
        
        $category = ProductCategory::find($categoryId);
        if (!$category) {
            return $this->error('分类不存在');
        }
        
        $category->status = $status;
        if ($category->save()) {
            return $this->success([], '状态更新成功');
        }
        return $this->error('状态更新失败');
    }
}